import {defineStore} from "pinia";
import {store} from '@/store';
import {localSet} from 'nices';
// import {useStorage} from '@vueuse/core';
import {resetRouter} from '@/router';

export const useUserStore = defineStore({
  id: 'user',
  state: () => ({
    token: useStorage('token', ''),
    nickname: '', // 昵称, 一般是登录页输入的账号名
    avatar: '', // 用户头像
    roles: [], // 路由权限
    perms: [], // 指令权限, 比如按钮权限
  }),
  actions: {
    setToken(value) {
      this.token = value;
    },
    /* getUserInfo() {
      return new Promise((resolve, reject) => {
        getInfo(this.token).then(response => {
          const {data} = response || {};

          if (!data) return reject('Verification failed, please Login again.');

          data.roles = ['admin', 'user'];

          if (!data.roles || data.roles.length <= 0) {
            reject('getInfo: roles must be a non-null array!');
          }

          this.nickname = data.nickname;
          this.avatar = data.image || 'https://s2.loli.net/2022/04/07/gw1L2Z5sPtS8GIl.gif';
          this.roles = data.roles || [];
          this.perms = data.perms || [];
          window.localStorage.setItem('userInfo', JSON.stringify(data || {}));
          resolve(data);
        }).catch(error => reject(error))
      })
    }, */
    getUserInfo() { // 实际项目中采用上面的getUserInfo方法为接口请求用户信息
      return new Promise(resolve => {
        const data = {
          roles: ['admin', 'user'],
          nickname: 'snytadminster',
          perms: []
        };
        this.nickname = data.nickname;
        this.avatar = data.image || 'https://s2.loli.net/2022/04/07/gw1L2Z5sPtS8GIl.gif';
        this.roles = data.roles || [];
        this.perms = data.perms || [];
        localSet('userInfo', data || {});
        resolve(data);
      });
    },
    logout() {
      return new Promise((resolve, reject) => {
        /* logoutApi()
          .then(() => {
            resetRouter();
            resetToken();
            localStorage.clear();
            resolve();
          })
          .catch(error => {
            reject(error);
          }); */

        resetRouter();
        this.resetToken();
        resolve();
      });
    },
    resetToken() {
      this.token = '';
      this.nickname = '';
      this.avatar = '';
      this.roles = [];
    }
  }
});


// 非setup
export function useUserStoreHook() {
  return useUserStore(store);
}